import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/const/MahjongConst.dart';
import 'package:mahjong/entity/MessageContext.dart';
import 'package:mahjong/entity/mahjong/DissolutionEntity.dart';
import 'package:mahjong/util/CustomNavigatorObserver.dart';
import 'package:mahjong/util/MessageUtils.dart';
import 'package:mahjong/widget/CommonAlterDialog.dart';
import 'package:mahjong/widget/MahjongCommon.dart';
import 'package:provider/provider.dart';
import 'package:mahjong/util/ConstState.dart';

typedef _CallBack = void Function(String roomCode);

class GameDissolution extends StatefulWidget {
  final _CallBack callback;
  final DissolutionEntity dissolutionEntity;
  final String currentUserId;
  GameDissolution({this.callback, this.dissolutionEntity, this.currentUserId});
  @override
  _GameDissolutionState createState() => _GameDissolutionState();
}

class _GameDissolutionState extends State<GameDissolution>
    with SingleTickerProviderStateMixin {
  double dialogHeight, dialogWidth;
  Timer countDown;
  int _remainingTime;
  // 发送退出指令
  MessageContext message =
      new MessageContext(action: MessageAction.DISSOLUTION);

  bool closeFarme = false;

  @override
  void dispose() {
    super.dispose();
    countDown?.cancel();
    ConstState.getInstance().dissolutionShow = false;
  }

  @override
  void initState() {
    super.initState();
    ConstState.getInstance().dissolutionShow = true;
    dialogHeight = 200.h;
    dialogWidth = 400.w;
    _remainingTime = widget.dissolutionEntity.remainingTime;
    countDown =
        new Timer.periodic(new Duration(seconds: 1), (Timer timer) async {
      _remainingTime--;
      if (_remainingTime == 0) {
        Navigator.of(context).pop();
      }
      setState(() {});
    });
  }

  String caseLongDateStr(int date) {
    int minute = date ~/ 60;
    int second = date % 60;
    return "0" +
        minute.toString() +
        ":" +
        (second > 9 ? second.toString() : "0" + second.toString());
  }

  List<Widget> caseUserItem(DissolutionEntity provider) {
    List<Widget> _child = [];
    provider.userDissolution.forEach((key, userInfo) {
      _child.add(userDisItem(
          userInfo.username, userInfo.portraitUrl, userInfo.agreeState));
    });
    return _child;
  }

  @override
  Widget build(BuildContext context) {
    return CommonAlterDialog(
        height: dialogHeight,
        width: dialogWidth,
        backgroundColor: Colors.white,
        child: Consumer(builder: (BuildContext buildContext,
            DissolutionEntity provider, Widget child) {
          if (provider.remainingTime < _remainingTime) {
            _remainingTime = provider.remainingTime;
          }
          // 判断是否有没有未处理的  任务
          bool confirmed = true;
          provider.userDissolution.forEach((key, value) {
            if (confirmed && value.agreeState == RoomDissolutionConst.dvlue) {
              confirmed = false;
            }
          });
          if (confirmed && !closeFarme) {
            closeFarme = true;
            Future.delayed(Duration(seconds: 1), () {
              ConstState.getInstance().dissolutionShow = false;
              Navigator.of(CustomNavigatorObserver.getContext()).pop();
            });
          }
          return Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("申请解散"),
                  Text(
                    "------" + caseLongDateStr(_remainingTime) + "------",
                    style: TextStyle(color: Colors.red, fontSize: 14.sp),
                  )
                ],
              ),
              Column(
                children: caseUserItem(provider),
              )
            ],
          );
        }));
  }

  Widget buildBtn(String userId, int agreeState) {
    if (agreeState == RoomDissolutionConst.dvlue &&
        widget.currentUserId == userId) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            padding: EdgeInsets.all(2.h),
            height: 30.h,
            child: ElevatedButton(
                onPressed: () {
                  message.body = RoomDissolutionConst.agree;
                  MessageUtils.sendMessage(message.toString());
                },
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.resolveWith((states) {
                      //设置按下时的背景颜色
                      if (states.contains(MaterialState.pressed)) {
                        return Colors.blue[200];
                      }
                      //默认不使用背景颜色
                      return Colors.orange.withOpacity(0.5);
                    }),
                    shape: MaterialStateProperty.all(StadiumBorder()) //边框
                    ),
                child: Text(
                  "同意",
                  style: TextStyle(fontSize: 16.sp),
                )),
          ),
          Container(
            padding: EdgeInsets.all(2.h),
            height: 30.h,
            child: ElevatedButton(
                onPressed: () {
                  message.body = RoomDissolutionConst.refuse;
                  MessageUtils.sendMessage(message.toString());
                },
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.resolveWith((states) {
                      //设置按下时的背景颜色
                      if (states.contains(MaterialState.pressed)) {
                        return Colors.orange[200];
                      }
                      //默认不使用背景颜色
                      return Colors.white.withOpacity(0);
                    }),
                    shape: MaterialStateProperty.all(StadiumBorder()) //边框
                    ),
                child: Text(
                  "拒绝",
                  style: TextStyle(fontSize: 16.sp),
                )),
          ),
        ],
      );
    }
    return Text(
      agreeState == RoomDissolutionConst.agree
          ? "已同意"
          : agreeState == RoomDissolutionConst.refuse
              ? "已拒绝"
              : "处理中...",
      textAlign: TextAlign.center,
      style: TextStyle(color: Colors.red),
    );
  }

  Container userDisItem(String userId, String portraitUrl, int agreeState) {
    return Container(
      height: 40.h,
      margin: EdgeInsets.only(bottom: 5.h),
      padding: EdgeInsets.symmetric(horizontal: 10.h),
      color: Colors.orange.withOpacity(0.2),
      child: Row(
        children: [
          MahjongCommon.headerImage(portraitUrl, width: 40.h, height: 40.h),
          Expanded(
            child: Text(
              userId,
              textAlign: TextAlign.center,
            ),
            flex: 1,
          ),
          Expanded(
            child: buildBtn(userId, agreeState),
            flex: 2,
          ),
        ],
      ),
    );
  }
}
